package com.hongxin.nw.netty.context;

import com.alibaba.fastjson.JSONObject;
import com.hongxin.nw.netty.config.ApplicationContextProvider;
import com.hongxin.nw.netty.down.BillingReq;
import com.hongxin.nw.netty.down.ChannelRequest;
import com.hongxin.nw.netty.down.StartReq;
import com.hongxin.nw.netty.down.TimeSyncReq;
import com.hongxin.nw.netty.model.Transfer;
import com.hongxin.nw.netty.server.AuthService;
import com.hongxin.nw.netty.utils.MyJson;
import com.hongxin.nw.netty.utils.pools.ChannelPools;
import com.hongxin.nw.netty.utils.pools.CodePools;
import com.hongxin.nw.netty.utils.pools.CodeTypePools;
import com.hongxin.nw.netty.utils.pools.HeartBeatPools;
import com.hongxin.nw.netty.values.TypeIdentif;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class StartState implements State {
 
   public void doAction(ChannelContext context) throws Exception {
      log.info("Player is in start state");
      String code = CodePools.getCode(context.getCtx().channel().id().asShortText());
      ChannelPools.addCtx(code, context.getCtx());//设备编号与通道的对应关系
      HeartBeatPools.addHB(context.getCtx().channel().id().asShortText(), System.currentTimeMillis()/1000);//设备编号与心跳时间

      Map<String, Object> data = new ConcurrentHashMap<>();
      AuthService authService = ApplicationContextProvider.getBean(AuthService.class);
      MyJson policy = authService.findPolicy(code);//请求登录设备的计费模型
      JSONObject json = policy.getJobData();
      data.put("data",json);

      Transfer transfer = new Transfer(code, null, data,
              TypeIdentif.M_DEFAULT.getInt(), CodeTypePools.getCodeType(code), Transfer.noNeedRecord, Transfer.noNeedMq, null);

      //U帧启动
      ChannelRequest cr1 = new ChannelRequest(new StartReq());
      cr1.execute(transfer);
      //时钟同步
      ChannelRequest cr = new ChannelRequest(new TimeSyncReq());
      cr.execute(transfer);
      //下发计费
      ChannelRequest bc = new ChannelRequest(new BillingReq());
      bc.execute(transfer);
   }
 
   public String toString(){
      return "Start State";
   }
}